package com.example.administrator.newxlmedical;

import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import beans.FingerprintUserBean;
import beans.NewUserInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import dialogs.ProgressDialog;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import netframe.NetReconnectFunc1;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.DigitalTrans;
import utils.FormateUtils;
import utils.MediaPlayerUtils;
import utils.TimeUtil;
import utils.ToastUtil;

public class  FingerprintEnterActivity extends BaseEnterActivity {

    @BindView(R.id.iv_fingerprint_enter_close)
    ImageView ivClose;
    @BindView(R.id.iv_fingerprint_enter)
    ImageView ivFingerprintEnter;
    @BindView(R.id.tv_finger_enter_error_content)
    TextView tvErrorContent;
    private MyHandler allHandler;
    private int fingerprintSize;//指纹用户的个数
    private int transferFingerprintFeatureSize;//下传特征值的个数
    private List<FingerprintUserBean> fingerprintFeatureList = new ArrayList<>();
    private MediaPlayer mediaPlayer;

    private ProgressDialog progressDialog;
    private boolean isFrist;
    private int count;
    private int sound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fingerprint_enter);
        ButterKnife.bind(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(NetAddress.token)) {
            String changeTime = sharedPreferences.getString(Constants.FINGERPRINT_USER_BEAN_CHANGETIME, "");
            if (!TextUtils.isEmpty(changeTime)) {
                getFingerprintFeature("select * from UserInfo where (FingerprintOne is not null or FingerprintTwo is not null) and ChangeTime > '" + changeTime + "' order by ChangeTime asc");
            } else {
                getFingerprintFeature("select * from UserInfo where FingerprintOne is not null or FingerprintTwo is not null order by ChangeTime asc");
            }
        } else {
            ToastUtil.showToast(FingerprintEnterActivity.this, "该机器尚未激活,请先激活");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        // TODO:
        allHandler.sendEmptyMessage(HandlerConstant.CANCLE_FINGERPRINT_COMMAND);
    }

    @Override
    public void initView() {
        super.initView();
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        allHandler.removeMessages(HandlerConstant.NO_OPERATION);
        progressDialog = new ProgressDialog(FingerprintEnterActivity.this, R.style.dialog, "正在下传指纹特征值，请稍候 . . .");
        progressDialog.show();
        sound = sharedPreferences.getInt(Constants.SOUND_KEY, 50);
    }

    @OnClick(R.id.iv_fingerprint_enter_close)
    public void onViewClicked() {
        finish();
    }

    //获取所有指纹的特征值
    private void getFingerprintFeature(String sql) {
        GetRetrofit.getInstance().getUserInfo2(NetAddress.token, NetAddress.machineCode, sql).subscribeOn(Schedulers.io())
                .retryWhen(new NetReconnectFunc1()).observeOn(AndroidSchedulers.mainThread())
                .groupBy(new Func1<NewUserInfoBean, Boolean>() {
                    @Override
                    public Boolean call(NewUserInfoBean newUserInfoBean) {
                        return newUserInfoBean.getData() == null ? false : newUserInfoBean.getData().size() > 0;
                    }
                }).flatMap(new Func1<GroupedObservable<Boolean, NewUserInfoBean>, Observable<NewUserInfoBean.DataBean>>() {
            @Override
            public Observable<NewUserInfoBean.DataBean> call(GroupedObservable<Boolean, NewUserInfoBean> booleanUserInfoBeanGroupedObservable) {
                Log.e("GGG", "call: getFingerprintFeature");
                if (booleanUserInfoBeanGroupedObservable.getKey()) {
                    return booleanUserInfoBeanGroupedObservable.map(new Func1<NewUserInfoBean, List<NewUserInfoBean.DataBean>>() {
                        @Override
                        public List<NewUserInfoBean.DataBean> call(NewUserInfoBean newUserInfoBean) {
                            return newUserInfoBean.getData();
                        }
                    }).flatMap(new Func1<List<NewUserInfoBean.DataBean>, Observable<NewUserInfoBean.DataBean>>() {
                        @Override
                        public Observable<NewUserInfoBean.DataBean> call(List<NewUserInfoBean.DataBean> dataBeen) {
                            fingerprintSize = 0;
                            transferFingerprintFeatureSize = 0;
                            fingerprintFeatureList.clear();
                            return Observable.from(dataBeen);
                        }
                    }).doOnNext(new Action1<NewUserInfoBean.DataBean>() {
                        @Override
                        public void call(NewUserInfoBean.DataBean dataBean) {
                            String fingerprintOne = dataBean.getFingerprintOne();
                            String fingerprintTwo = dataBean.getFingerprintTwo();
                            if (!TextUtils.isEmpty(fingerprintOne)) {
                                FingerprintUserBean fingerprintUserBean = new FingerprintUserBean();
                                fingerprintUserBean.setFingerprintUserId(dataBean.getID());
                                fingerprintUserBean.setFingerprintFeature(dataBean.getFingerprintOne());
                                fingerprintFeatureList.add(fingerprintUserBean);
                            }
                            if (!TextUtils.isEmpty(fingerprintTwo)) {
                                FingerprintUserBean fingerprintUserBean = new FingerprintUserBean();
                                fingerprintUserBean.setFingerprintUserId(dataBean.getFingerprintId());
                                fingerprintUserBean.setFingerprintFeature(dataBean.getFingerprintTwo());
                                fingerprintFeatureList.add(fingerprintUserBean);
                            }
                        }
                    }).last().doOnNext(new Action1<NewUserInfoBean.DataBean>() {
                        @Override
                        public void call(NewUserInfoBean.DataBean dataBean) {
                            SharedPreferences.Editor edit = sharedPreferences.edit();
                            edit.putString(Constants.FINGERPRINT_USER_BEAN_CHANGETIME, dataBean.getChangeTime());
                            edit.commit();
                        }
                    });

                } else {
                    allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_VERIFICATION);
                    sendEmptyMessageDelay(HandlerConstant.FINGERPRINT_UNLOGIN_TIME, UNLOGIN_TIME);
                    if (mediaPlayer != null) {
                        mediaPlayer.release();
                    }
                    MediaPlayerUtils.playSound(FingerprintEnterActivity.this,R.raw.fingerprint_login);
                    return null;
                }
            }
        }).subscribe(new Action1<NewUserInfoBean.DataBean>() {
            @Override
            public void call(NewUserInfoBean.DataBean dataBean) {
                fingerprintSize = fingerprintFeatureList.size();
                Message message = allHandler.obtainMessage();
                message.obj = DigitalTrans.integerToHex(fingerprintFeatureList.get(0).getFingerprintUserId(), 4);
                message.what = HandlerConstant.DELETE_FINGERPRINT_USER;
                allHandler.sendMessage(message);
            }
        }, new MyAction1() {
            @Override
            public void call(Throwable throwable) {
                super.call(throwable);
                progressDialog.dismiss();
                ToastUtil.showToast(FingerprintEnterActivity.this, "网络请求错误");
            }
        });
    }

    //指纹出错时，重置变量等
    private void resetFingerprint() {
        allHandler.sendEmptyMessageDelayed(HandlerConstant.FINGERPRINT_VERIFICATION, 2000);
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        MediaPlayerUtils.playSound(this,R.raw.fingerprint_login_again);
    }

    //删除指纹模组里的用户(下传之前先删除)
    private void deleteFeingerprintuser() {
        transferFingerprintFeatureSize++;
        if (transferFingerprintFeatureSize < fingerprintSize) {
            Message message1 = allHandler.obtainMessage();
            message1.obj = DigitalTrans.integerToHex(fingerprintFeatureList.get(transferFingerprintFeatureSize).getFingerprintUserId(), 4);
            Log.e(TAG, "deleteFeingerprintuser: " + message1.obj);
            message1.what = HandlerConstant.DELETE_FINGERPRINT_USER;
            allHandler.sendMessage(message1);
        } else {
            saveToFile("---------------------------");
            transferFingerprintFeatureSize = 0;
            Message message1 = allHandler.obtainMessage();
            message1.arg1 = fingerprintFeatureList.get(0).getFingerprintUserId();
            message1.obj = fingerprintFeatureList.get(0).getFingerprintFeature();
            message1.what = HandlerConstant.TRANSFER_FINGERPRINT_FEATURE;
            allHandler.sendMessage(message1);
        }
    }

    //下传用户指纹
    private void transferFingerprintFeature() {
        transferFingerprintFeatureSize++;
        if (transferFingerprintFeatureSize < fingerprintSize) {
            Message message1 = allHandler.obtainMessage();
            message1.arg1 = fingerprintFeatureList.get(transferFingerprintFeatureSize).getFingerprintUserId();
            message1.obj = fingerprintFeatureList.get(transferFingerprintFeatureSize).getFingerprintFeature();
            message1.what = HandlerConstant.TRANSFER_FINGERPRINT_FEATURE;
            allHandler.sendMessage(message1);
        } else {
            //若要想所有指纹模组能够共用,要请求网络,设置模组的特征值
            allHandler.sendEmptyMessage(HandlerConstant.FINGERPRINT_VERIFICATION);
            sendEmptyMessageDelay(HandlerConstant.FINGERPRINT_UNLOGIN_TIME, UNLOGIN_TIME);
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
            MediaPlayerUtils.playSound(this,R.raw.fingerprint_login);
        }
    }

    @Override
    public void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case HandlerConstant.FINGERPRINT_UNLOGIN_TIME:
                if (mediaPlayer != null) {
                    mediaPlayer.release();
                }
                MediaPlayerUtils.playSound(this,R.raw.enter_again);
                allHandler.sendEmptyMessage(HandlerConstant.CANCLE_FINGERPRINT_COMMAND);
                allHandler.removeMessages(HandlerConstant.FINGERPRINT_VERIFICATION);
                break;
            case HandlerConstant.FINGERPRINT_VERIFICATION:
                progressDialog.dismiss();
                break;
            case HandlerConstant.FINGERPRINT_VERIFICATION_SUCCESS:
                ToastUtil.showToast(FingerprintEnterActivity.this,"识别通过，正在登录 ...");
                int i = Integer.parseInt((String) msg.obj, 16);
                Log.e("GGG", "readAccordCommandType: " + i);
                mHandler.removeMessages(HandlerConstant.FINGERPRINT_UNLOGIN_TIME);
                String sql;
                if (i < 5000) {
                    sql = "select ID,Name,UCode,SubTime,DelFlag,Department,Enable,RoleInfoId from UserInfo where ID = " + i;
                } else {
                    sql = "select ID,Name,UCode,SubTime,DelFlag,Department,Enable,RoleInfoId from UserInfo where FingerprintId = " + i;
                }
                userLogin(sql, 1);

                getCabinetInfoId();
                break;
            case HandlerConstant.TRANSFER_FINGERPRINT_FEATURE_SUCCESS:
                ToastUtil.showToastlog(FingerprintEnterActivity.this, "transfer :  " + transferFingerprintFeatureSize + "  ::  " + fingerprintFeatureList.size());
                transferFingerprintFeature();
                break;
            case HandlerConstant.ACK_FAIL:
                transferFingerprintFeature();
                break;
            case HandlerConstant.DELETE_FINGERPRINT_USER_SUCCESS:
                ToastUtil.showToastlog(FingerprintEnterActivity.this, "delete :  " + transferFingerprintFeatureSize + "  ::  " + fingerprintFeatureList.size());
                deleteFeingerprintuser();
                break;
            case HandlerConstant.DELETE_FINGERPRINT_USER_FAIL:
                ToastUtil.showToastlog(FingerprintEnterActivity.this, transferFingerprintFeatureSize + "  ::  " + fingerprintFeatureList.size());
                deleteFeingerprintuser();
                break;
            case HandlerConstant.ACK_FULL:
                resetFingerprint();
                break;
            case HandlerConstant.ACK_NOUSER:
//                resetFingerprint();
                deleteFeingerprintuser();
                break;
            case HandlerConstant.ACK_TIMEOUT:
                count++;
                if (count == 3) {
                    allHandler.sendEmptyMessage(HandlerConstant.FINGER_PRINT_TIME_OUT);
                } else {
                    resetFingerprint();
                }
                break;
            case HandlerConstant.FINGERPRINT_VERIFICATION_FAIL:
                resetFingerprint();
                break;
            case HandlerConstant.ACK_IMAGEFIAL:
                resetFingerprint();
                break;
            case HandlerConstant.ACK_BREAK:
                resetFingerprint();
                break;
            case HandlerConstant.FINGER_PRINT_TIME_OUT:
                finish();
                break;
            case HandlerConstant.FINGER_LOGIN_ERROR:

                ivFingerprintEnter.setImageResource(R.mipmap.noneuser);
                tvErrorContent.setText("您已被禁用!");
                break;

            case HandlerConstant.FINGER_LOGIN_NO_USER:
                ivFingerprintEnter.setImageResource(R.mipmap.noneuser);
                tvErrorContent.setText("用户不存在!");
                break;

            case HandlerConstant.FINGER_LOGIN_ERROR_AGIN :
                ToastUtil.showToast(FingerprintEnterActivity.this,"登录失败，请重新验证!");
                resetFingerprint();
                break;
        }
    }

    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    public void saveToFile(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {

                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  --begin--:  ");
                sb.append(receiveData);
                sb.append("  --end--;  ");
                sb.append("\r\n");
                String fileName = TimeUtil.getYear() + "-" + (TimeUtil.getMonth() + 1) + "-" + TimeUtil.getDay() + ".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/fingerprint/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
